<template>
  <div class="cart">
    <div class="head">
      <van-nav-bar title="购物车" />
    </div>
    <div class="container">
      <div class="cart-list" v-for="(item,index) in carts" :key="item._id">
        <van-icon @click="delevent(item._id,index)" name="delete" />
        <input type="checkbox" @click="judge" class="selbtn" />
        <router-link :to="'/prolist/desc/'+item.product._id">
        <van-card
          :price="item.product.product_price"
          :origin-price="9999.00"
          :desc="item.product.smallTitle"
          :title="item.product.desc"
          :thumb="item.product.coverImgUrl"
        >
          <div slot="tags">
            <p style="margin-top:0.2rem;font-size:0.13rem">件数X{{item.quantity}}</p>
          </div>
        </van-card>
        </router-link>
      </div>
    </div>
    <div class="foot">
      <van-submit-bar :price="totalprice*100" @submit="submit" button-text="提交订单">
        <input type="checkbox" @click="fllow" class="allbtn" />全选
      </van-submit-bar>
    </div>
  </div>
</template>
<style scoped>
@import "../css/cart.css";
</style>
<script>
import axios from "axios";
import { mapState, mapMutations, mapAction } from "vuex";
export default {
  data() {
    return {
      result: [],
      checked: true,
      carts: [],
      totalprice: 0,
      checkedgoods: []
    };
  },
  created() {
    let token = localStorage.getItem("token");
    console.log(token);
    axios
      .get("http://192.168.17.95:3000/api/v1/cart/cartlist", {
        headers: {
          yangnb: `ynb ${token}`
        }
      })
      .then(res => {
        console.log(res);
        console.log(res.data.carts);
        this.carts = res.data.carts;
        this.savecarts({
          carts: res.data.carts
        });
      })
      .catch(err => {
        console.log(err);
      });
  },
  methods: {
    ...mapMutations("product", ["save", "savecarts", "saveChecked"]),
    fllow() {
      let all = document.querySelector(".allbtn");
      let sel = document.querySelectorAll(".selbtn");
      [...sel].forEach(v => {
        v.checked = all.checked;
      });
      this.count();
    },
    // 点击全选使单选按钮跟随全选按钮状态
    judge() {
      let sel = document.querySelectorAll(".selbtn");
      let all = document.querySelector(".allbtn");
      let flag = [...sel].every(v => v.checked == true);
      all.checked = flag;
      this.count();
    },
    // 点击单选判断是否所有单选都被选中，如果全部选中全选按钮跟随状态
    delevent(id, index) {
      axios
        .delete(`http://192.168.17.95:3000/api/v1/cart/delcart/${id}`)
        .then(res => {
          console.log(res);
          if (res.data.code == 1) {
            this.carts.splice(index, 1);
            this.count();
          } else {
            alert("删除失败");
          }
        });
    },
    count() {
      let count = 0;
      let sel = document.querySelectorAll(".selbtn");
      for (let i = 0; i < this.carts.length; i++) {
        if (sel[i].checked) {
          // this.checkedgoods.push(this.carts[i]);在这里push的话是函数执行一次就push一遍，点三次按钮，函数执行三次，每次又循环三个单位，所以会出错
          count =
            count +
            this.carts[i].quantity * this.carts[i].product.product_price;
        }
      }
      console.log(count);
      this.totalprice = count;
    },
    // 计算总价，在合适的点击情况下调用
    submit() {
      let sel = document.querySelectorAll(".selbtn");
      for (let i = 0; i < this.carts.length; i++) {
        if (sel[i].checked) {
          this.checkedgoods.push(this.carts[i]);
        }
      }
      console.log(this.checkedgoods);
      if (this.checkedgoods.length == 0) {
        this.$toast("您还没有选择要购买的商品~");
      } else {
        this.$router.push({ name: "SubmitOrder" });
      }
      localStorage.setItem('checkedgoods',JSON.stringify(this.checkedgoods))
      // this.saveChecked({
      //   checkedgoods: this.checkedgoods
      // });
    }
  },
  computed: {
    ...mapState("product", ["car"])
  }
};
</script>
